package chpt05.shopping.dao;

import java.util.ArrayList;
import java.util.List;
import chpt05.shopping.Commodity;

public class CommodityDAOArrayListImpl implements CommodityDAO {
	private List<Commodity> commodityList;

	public CommodityDAOArrayListImpl() {
		commodityList = new ArrayList<>();
	}

	@Override
	public void init() {
		// 初始化商品列表
		commodityList.clear();
		List<Commodity> datas = CommodityDataGenerator.generateData();
        for (Commodity commodity : datas) {
			this.add(commodity);
		}
	}

	@Override
	public List<Commodity> findAll() {
		// 显示所有商品
		return commodityList;
	}

	@Override
	public boolean add(Commodity commodity) {
		if (findById(commodity.getId()) != null) {
			return false; // ID 相同的商品已存在，添加失败
		}
		commodityList.add(commodity);
		return true; // 添加成功
	}

	@Override
	public List<Commodity> findByName(String name) {
		// 根据名称查找商品列表
		List<Commodity> result = new ArrayList<>();
		for (Commodity commodity : commodityList) {
			if (commodity.getName().contains(name)) {
				result.add(commodity);
			}
		}
		return result;
	}

	@Override
	public Commodity findById(Integer id) {
		// 根据id查找商品
		for (Commodity commodity : commodityList) {
			if (commodity.getId().equals(id)) {
				return commodity;
			}
		}
		return null;
	}

}